<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区 -->
    <el-card>
      <!-- 警告区 -->
      <el-alert
        title="
注意：只允许为第三级分类设置相关参数！"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 选择商品分类区 -->
      <el-row>
        <el-col>
          <span>选择商品分类: </span>
          <el-cascader
            :options="ParentCateList"
            :props="cascaderProps"
            v-model="selectedKeys"
            clearable
            @change="parentCtaeChange"
          >
          </el-cascader>
        </el-col>
      </el-row>
      <!-- tap页标签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数面板 -->
        <!-- 通过name携带属性 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="isButtonDisabled"
            @click="addParamsdialogVisible = true"
            >添加参数</el-button
          >
          <el-table :data="manyTabledate" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  type="primary"
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleTag(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 动态编辑标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="eidtParamsdialogVisible(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态参数面板 -->
        <el-tab-pane label="静态参数" name="only">
          <el-button
            type="primary"
            :disabled="isButtonDisabled"
            @click="addParamsdialogVisible = true"
            >添加属性</el-button
          >
          <el-table :data="onlyTabledate" border stripe>
            <!-- 展开 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  type="primary"
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleTag(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 动态编辑标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="eidtParamsdialogVisible(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加属性弹出框共用一个弹出框 -->
    <el-dialog
      :title="this.activeName === 'many' ? '添加动态参数' : '添加静态参数'"
      :visible.sync="addParamsdialogVisible"
      width="50%"
      @close="addParamsdialogVisibleClose"
    >
      <el-form
        :model="addParamsForm"
        :rules="addParamsFormRules"
        ref="addParamsFormRef"
        label-width="80px"
        status-icon
      >
        <!--disabled只读  -->
        <el-form-item
          :label="this.activeName === 'many' ? '动态参数' : '静态参数'"
          prop="attr_name"
        >
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑弹出框 -->
    <el-dialog
      :title="this.activeName === 'many' ? '编辑动态参数' : '编辑静态参数'"
      :visible.sync="editParamsdialogVisible"
      width="50%"
      @close="editParamsdialogVisibleClose"
    >
      <el-form
        :model="editParamsForm"
        :rules="editParamsFormRules"
        ref="editParamsFormRef"
        label-width="80px"
        status-icon
      >
        <el-form-item
          :label="this.activeName === 'many' ? '动态参数' : '静态参数'"
          prop="attr_name"
        >
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 父级分类的列表数据
      ParentCateList: [],
      // 指定级联选择器的配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 选中的父级Id数组
      selectedKeys: [],
      // 默认展开的tab项
      activeName: 'many',
      // 选中tabs数据
      manyTabledate: [],
      onlyTabledate: [],
      // 添加参数框的显示状态
      addParamsdialogVisible: false,
      // 添加表单数据
      addParamsForm: {
        attr_name: ''
      },
      // 验证规则
      addParamsFormRules: {
        // 验证参数
        attr_name: [
          {
            required: true,
            message: '此项不能为空',
            trigger: 'blur'
          }
        ]
      },
      // 编辑对话框
      editParamsdialogVisible: false,
      editParamsForm: { attr_name: '' },
      // 验证规则
      editParamsFormRules: {
        attr_name: [
          {
            required: true,
            message: '此项不能为空',
            trigger: 'blur'
          }
        ]
      }
      // 全局变化
      // //  动态编辑标签
      // inputVisible: false,
      // // 文本框输入的值
      // inputValue: "",
    }
  },
  created () {
    this.getParentCatelist()
  },
  methods: {
    // 获取所有的商品分类列表
    // 获取父级分类的数据列表
    async getParentCatelist () {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 3 }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败！')
      }
      this.ParentCateList = res.data
    },
    // 选中的事件
    parentCtaeChange () {
      //  选中时调用函数
      this.getCateData()
    },
    // tab页点击页的处理函数
    handleTabClick () {
      this.getCateData()
      // console.log(this.activeName);
    },
    // 解决选中事件只有一次触发的bug
    async getCateData () {
      //  只要三级分类下的节点
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        // 其他数据也清空
        this.manyTabledate = []
        this.onlyTabledate = []
        return 0
      }
      // 当选中时就渲染出参数列表
      // 根据所选分类的Id,和当前面板的参数, 获取对应的参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateID}/attributes`,
        { params: { sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败！')
      }
      res.data.forEach((item) => {
        // 通过空格分割成数组
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制每一行文本框的显示与隐藏给他添加属性inputVisible，inputValue
        item.inputVisible = false
        item.inputValue = ''
      })
      // console.log(res.data);
      if (this.activeName === 'many') {
        this.manyTabledate = res.data
      } else {
        this.onlyTabledate = res.data
      }
      this.$message.success('获取参数列表成功')
    },
    // 重置事件
    addParamsdialogVisibleClose () {
      this.$refs.addParamsFormRef.resetFields()
    },
    addParams () {
      this.$refs.addParamsFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateID}/attributes`,
          {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) return this.$message.error('添加参数失败')
        this.$message.success('添加参数成功')
        this.addParamsdialogVisible = false
        this.getCateData()
      })
    },
    // 编辑弹出修改对话框
    // 展示数据有bug单独储存可以解决吧
    async eidtParamsdialogVisible (attrId) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateID}/attributes/${attrId}`,
        {
          params: { attr_sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败！')
      }
      this.editParamsForm = res.data
      this.editParamsdialogVisible = true
    },
    editParamsdialogVisibleClose () {
      this.$refs.editParamsFormRef.resetFields()
    },
    //  确定修改参数
    editParams () {
      this.$refs.editParamsFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateID}/attributes/${this.editParamsForm.attr_id}`,
          {
            attr_name: this.editParamsForm.attr_name,
            attr_sel: this.activeName
          }
        )
        // console.log(this.activeName);
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success('修改参数成功')
        this.editParamsdialogVisible = false
        this.getCateData()
      })
    },
    // 删除
    async removeParams (attrID) {
      const conformResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (conformResult !== 'confirm') {
        return this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateID}/attributes/${attrID}`
      )
      if (res.meta.status !== 200) return this.$message.error('删除参数失败')
      this.$message.success('删除参数成功')
      // 保留当前页
      this.getCateData()
    },
    // 文本框失去焦点和按下enter键
    handleInputConfirm (row) {
      // 失去焦点恢复到按钮并判断值trim去掉空格
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 添加成功
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 发送请求将数据保存在数据库
      this.saveAttrVals(row)
    },
    // 将数据attr_vals保存在数据库
    async saveAttrVals (row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateID}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success('修改参数成功')
    },
    // 按钮点击事件展示文本框
    // $nextTick方法的作用，就是当元素被重新渲染出来，才会指定回调函数中的代码
    showInput (row) {
      row.inputVisible = true
      // 让文本框自动获得焦点
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除对应参数可选项
    handleTag (index, row) {
      row.attr_vals.splice(index, 1)
      this.saveAttrVals(row)
    }
  },
  computed: {
    // 计算属性判断禁用状态
    isButtonDisabled () {
      if (this.selectedKeys.length !== 3) {
        return true
      }
      return false
    },
    // 当前选中的3级发类Id
    cateID () {
      if (this.selectedKeys.length === 3) {
        // 选中数组的最后一项
        return this.selectedKeys[this.selectedKeys.length - 1]
      }
      return null
    }
    // 计算属性方法做
    // titleText(){
    //   if(this.activeName="many"){
    //     return "动态参数"
    //   }
    //   else{
    //     return "静态参数"
    //   }
    // }
  }
}
</script>

<style Lang="less" scoped>
.el-alert {
  margin-bottom: 20px;
}
.el-tabs {
  margin-top: 20px;
}
.el-tag {
  margin-right: 15px;
}
.input-new-tag {
  width: 140px;
}
</style>>
